package com.rabbiter.util;

import com.rabbiter.config.MinioConfig;
import io.minio.*;
import io.minio.messages.Bucket;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Minio文件操作工具
 */
@Component
public class MinioUtil {

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;

    /**
     * 默认的仓库名字
     */
    private final static String BUCKET_NAME = "warehouse";

    /**
     * 创建bucket，可以新建一个存储文件的桶，名字必须小写
     */
    public void createBucket(String bucket) throws Exception{
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }

    /**
     * 上传文件
     */
    public String uploadFile(MultipartFile file) throws Exception {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build())) {
            return "存储路径错误";
        }
        //防止文件重名
        String filename = UUID.randomUUID().toString()+ Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(BUCKET_NAME)
                .object(filename)
                .stream(file.getInputStream(), file.getInputStream().available(), -1)
                .contentType(file.getContentType())
                .build());
        //返回文件地址
        return minioConfig.getUrl() + "/" + BUCKET_NAME + "/" + filename;
    }

    /**
     * 列出所有bucket
     */
    public List<String> getAllBucket() throws Exception{
        List<Bucket> buckets = minioClient.listBuckets();
        return buckets.stream().map(Bucket::name).collect(Collectors.toList());
    }


    /**
     * 下载文件
     */
    public InputStream downLoad(String bucket, String objectName) throws Exception{
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(objectName).build());
    }

    /**
     * 删除bucket
     */
    public void deleteBucket(String bucket) throws Exception{
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
    }

    /**
     * 删除文件
     */
    public void deleteObject(String bucket,String objectName) throws Exception{
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
    }

}
